<?php
namespace app\api\controller;
use app\common\model\Config;
use app\Request;
use fast\Http;
use think\facade\Db;
class SendMessage extends Api
{
    public function initialize(){
        $this->appId = Config::where('name', 'miniprogram_app_id')->value('value');
        $this->appSecret = Config::where('name', 'miniprogram_app_secret')->value('value');
    }


    public function newmsgpush(Request $request){
        if (!$request->isPost()) $this -> error("请求方式错误");
        $params = $request->post('params');

        $type = $params['type'];
        $openId = $params['openId'];
        $key1 = $params['key1'];
        $key2 = $params['key2'];
        $key3 = $params['key3'];
        $key4 = $params['key4'];
        $key5 = $params['key5'];


        switch ($type){
            case 1:
                $tmplid = "H30bmePNKK-DDgmd9dtdqtsqzEJR6HvStpVtLFeQ454";
                $typename = "预约挂号成功通知";
                $strjson = '{"touser":"'.$openId.'","template_id":"'.$tmplid.'","data":{"thing1":{"value":"'.$key1.'"},"phrase6":{"value":"'.$key2.'"},"amount12":{"value":"'.$key3.'"},"number13":{"value":"'.$key4.'"},"time17":{"value":" '.$key5.'"}}}';
                break;
        }
        $return =  $this -> sendMessage($strjson);
        $data = [
            'tempid' => $tmplid,
            'type' => $typename,
            'content' => $strjson,
            'createtime' => time(),
        ];
        Db::name('wechat_notify') -> insert($data);
//
        $this -> success('请求成功',$return);
    }





    //获取access_token
    public function gettoken(){
        session_start();
        if(!\session('?mini_access_token') || !\session('?mini_expires_in') && time() > \session('mini_expires_in')) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token';
            $param = [
                'grant_type' => 'client_credential',
                'appid' => $this-> appId,
                'secret' => $this-> appSecret
            ];
            $res = json_decode(Http::get($url, $param), 1);

            $access_token = $res['access_token'];
        } else {
            $access_token = \session('mini_access_token');
        }
        return $access_token;
    }




    /*
    * 发送订阅消息
    * @return [type] [description]
    */
    public function sendMessage($str){
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $this -> gettoken();
        $result = $this -> send_post($url,$str);
        file_put_contents('logs/dingyue.txt',date('Y-m-d H:i:s').$result.PHP_EOL, FILE_APPEND);
        return $result;
    }
    public function send_post($url, $post_data){
        $options = array(
            'http' => array(
                'method'  => 'POST',
                'header'  => 'Content-type:application/json',
                'content' => $post_data,
                'timeout' => 60
            )
        );

        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);

        return $result;
    }




    //请求
    public function https_post($url='',$post_data=''){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
//        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $res = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $res; // 返回数据，json格式
    }

}